package classes.helper
{
	import flash.events.Event;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import mx.controls.Alert;
	import mx.core.FlexGlobals;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	public class FormUploader { 
		private static var allFilter:FileFilter = new FileFilter('All Files (*.*)', '*.*');
		private static var allTypes:Array = [allFilter];
		
		private var fileReference:FileReference = null;
		private var _serverAddress:String = null;
		private var _sessionid:String = null;
		private var _params:URLVariables = null;
		
		public function FormUploader(serverAddress:String) {
			this._serverAddress = serverAddress;
		}
		
		private function browseFileReference():void {
			
			try {
				fileReference = new FileReference();
				fileReference.addEventListener(Event.SELECT, fileSelectedHandler);
				fileReference.addEventListener(Event.COMPLETE, fileCompleteHandler);
				fileReference.addEventListener(Event.CANCEL, fileCancelHandler);
				
				try {
					var success:Boolean = fileReference.browse(allTypes);
				} catch (error:Error) {
					trace(error.message);
				}
			} catch (error:Error) {
				trace(error.message);
			}
		}
		
		public function upload(params:URLVariables):void {
			if (!_serverAddress) return;
			_params = params;
			
			var httpService:HTTPService = new HTTPService();
			httpService.url = _serverAddress + "/sessionid";
			httpService.method = "GET";
			httpService.addEventListener("result", httpResult);
			httpService.addEventListener("fault", httpFault);
			httpService.send();
			
			browseFileReference();
		}
		
		private function httpResult(event:ResultEvent):void {
			_sessionid = event.result as String;
		}
		
		private function httpFault(event:FaultEvent):void {
			trace(event.fault.faultString);
		}
		
		private function fileSelectedHandler(event:Event):void {
			var request:URLRequest =
				new URLRequest(_serverAddress + '/form' + (_sessionid && _sessionid.length > 0 ? "?jsessionid=" + _sessionid : ''));
			
			request.method = URLRequestMethod.POST;
			request.data = _params;
			
			fileReference.upload(request);
		}
		
		private function fileCancelHandler(event:Event):void {
			fileReference = null;
		}
		
		private function fileCompleteHandler(event:Event):void {
			fileReference.removeEventListener(Event.SELECT, fileSelectedHandler);
			fileReference.removeEventListener(Event.COMPLETE, fileCompleteHandler);
			fileReference.removeEventListener(Event.CANCEL, fileCancelHandler);
			Alert.show("You can download your file from the link bellow:\n" + _serverAddress + "/" + fileReference.name, "Success");
		}
		
	}

}